$(function() {
//Declare variable
var  BillNo= $( "#txtBillNo" ),
	CustName = $( "#txtCustName" ),
	DateFrom = $( "#txtDateFrom" ),
	DateTo = $( "#txtDateTo" ),
	allFields = $( [] ).add( BillNo )
						.add(CustName)
						.add(DateFrom)
						.add(DateTo)
					,
	tips = $( ".validateTips" ),
	button_name="",
	url="a_cancelbill.php", 
	ID="",
	AddTitle="Cancel Bill ",	
	rowSelect="";
			
		if  ($("#cboBranch").length > 0 ){
			$.get('a_stock.php', {"c":"b"},function(data){
				//alert(data);
				$.each(eval('('+data+')'), function(index, text) {
					$("#cboBranch").append(
							$('<option></option>').val(text).html(index)
						 );
				});
			});	
			$("#cboBranch").append($('<option></option>').val(0).html('All'));
		}
		
			
		//load first page
		LoadData(1,true);
		
	
		//Show Loading bar			
		function showLoader(){
			$( "#resultData tbody:first" ).prepend( "<tr>"
						+"<td colspan='12' class='search-background'>"
						+"<label><img src='images/ajax-loader.gif'/></label>"
						+"</td>"
						+"</tr>" ); 
			 $('.search-background').fadeIn(900,0);
		}
		//Hide Loading bar			
		function hideLoader(){
			$('.search-background').fadeOut(300);
			$( "#resultData tbody tr" ).remove();
		};		
				
	
		
		$( "#dialog:ui-dialog" ).dialog( "destroy" );
		
		//Confirm Dialog
		$( "#dialog-confirm" ).dialog({
			resizable: false,
			height:160,
			autoOpen: false,
			modal: true
		});
		

		//Form Edit Add 
		$( "#dialog-form" ).dialog({
			autoOpen: false,
			resizable:false,
			height: 500,
			width: 600,
			zIndex:9999,
			modal: true,
			open: function() { 
				 // $("#pAmount").val("");
				 // $("#pAmount").focus();
				 // $( "#tbPayHistory tbody tr" ).remove();
			},
			close: function() {
				// $( "#tbPayHistory tbody tr" ).remove();
				 // $("#pAmount").val("");
				 // ID="";
			}
		});
		function setValue(obj){
			$("#name").val(obj.eq(2).html());
			$("#tAmount").val(obj.eq(5).html());
			$("#rAmount").val(obj.eq(7).html());
			
			 ID=obj.eq(1).html();
			
			var dataSet={'id':ID,'m':'detail'};  
			//alert(id);
			 $.ajax({
				type: 'POST',
				cache: false,
				url: url,
				data: dataSet,
				success: function(data){
					//	alert(data);
					var obj=eval('('+data+')');
					
					$("#tbPayHistory tbody:first" ).prepend( obj['html'] ); 
					$("#iCount").attr('innerHTML',obj['rows']);	
					$("#dlgTotalPay").attr('innerHTML',obj['paytoal']);	
					
				}
			});
		}
		
		// Set value from control to array 
		function getValue(){
			var o = {};
			//get name and value control 
			$( "#dialog-form" ).find('input').each(function(){
				if (o[$(this).attr('id')]) {
					if (!o[$(this).attr('id')].push) {
						o[$(this).attr('id')] = [o[$(this).attr('id')]];
					}
					o[$(this).attr('id')].push($(this).val() || '');
				} else {
					o[$(this).attr('id')] = $(this).val() || '';
				}
			});
			//Address 
			var _address = $( "#dialog-form" ).find('textarea').eq(0);
			o[_address.attr('id')] = _address.val() || '';
			
			return o;
		}
		// Check input data in control
		function checkRequireControl(){
			var bValid=true;
			bValid = bValid && checkInputFile( $("#pAmount"), "Payment Amount",1);
			return bValid;
		}
		function CommaFormatted(amount)	{
		 
			var delimiter = ","; // replace comma if desired
			var a = amount;//.split('.',2)
			var d = 0;//a[1];
			var i = parseInt(a);
			if(isNaN(i)) { return ''; }
			var minus = '';
			if(i < 0) { minus = '-'; }
			i = Math.abs(i);
			var n = new String(i);
			var a = [];
			while(n.length > 3)
			{
				var nn = n.substr(n.length-3);
				a.unshift(nn);
				n = n.substr(0,n.length-3);
			}
			if(n.length > 0) { a.unshift(n); }
			n = a.join(delimiter);
			if(d.length < 1) { amount = n; }
			else { amount = n; }
			amount = minus + amount;
			return amount;
		}
	//Search 	
	$("#btnSearch").click(function(){
		LoadData(1,true);
	});
	//Cancel bill
	$(".btnCancel").live('click',function(){
		rowSelect = $(this).parent().parent();
		var b_id=rowSelect.find("td").eq(1).html();
		
		$("#dialog-confirm").dialog("open");
		$("#dialog-confirm").dialog("option","buttons",	{
			"Cancel Bill": function() {
				 $.ajax({
					type: 'POST',
					cache: false,
					url: url,
					data: {'m':'cancel','id':b_id},
					success: function(data){
						var msg= eval('('+data+')');
						alert(msg['msg']);
						if (msg['result']=='1'){
							
							// remove row
							rowSelect.remove(); 
							//Desc number
							var rows=$("#rowCount").attr('innerHTML');
							$("#rowCount").attr('innerHTML',parseInt(rows,10)-1);
						}
					}
				});
				$( this ).dialog( "close" );
			},
			Close: function() {
					$( this ).dialog( "close" );
			}
		});
	});
	
	$(".btnPrint").live('click',function(){
		var pid=$(this).parent().parent().find("td").eq(1).html();
		
		newwindow=window.open('pos_print.php?i='+pid,'','height=450px,width=350px');
		if (window.focus) {newwindow.focus()}	
	});
	
	//View Bill / Cancel by Detail
	$(".btnView").live('click',function(){
		var b_id=$(this).parent().parent().find("td").eq(1).html();
		$("#hBillNo").val(b_id);
		$("#Act").submit();
	});
	
	$("#btnBack").live('click',function(){
		//alert('d');
		$("#Act").attr("action", "pos.php");
		$('#Act').submit();
	});
	function LoadData(page,b){
			$( "#resultData tbody tr" ).remove();
			//Show loading
			showLoader();
			//set criteria
			
			var branch=0;
			
			if ($("#cboBranch").length>0)
				branch=$("#cboBranch").val();
			
			var dataSet={'m':'search'
						,'id':BillNo.val()
						,'name':CustName.val()
						,'datefrom':DateFrom.val()
						,'dateto':DateTo.val()
						,'page':page
						,'barnchid':branch
						,'type':$("input:radio[name:canceltype]:checked").val()
						};
					
			 //Post 		
			 $.post(url,  dataSet , function(data){
 
				//hide loadinga
				hideLoader();
				//convert string json to java json
				var obj=eval("(" + data + ")");

				//set data to table
				$( "#resultData tbody" ).append(obj['data']);
				//set row 
				
				//var rowsCnt = new Number(obj["rows"]);
				$("#rowCount").attr('innerHTML', CommaFormatted(obj["rows"]));
				//set page
			if (b){
 
					if (parseInt(obj['totalpage'])>1){
						$("#paging_btn").show();
						setPaging(parseInt(obj['totalpage']));
					}else{
						$("#paging_btn").hide();
					}					
					 
				}
			 });
		}
 
			
	
	function setPaging(iTotal){
				 $("#paging_btn").paginate({
				count 		: iTotal,
				start 		: 1,
				display     : 10,
				border					: false,
				text_color  			: '#888',
				background_color    	: '#EEE',	
				text_hover_color  		: 'blue',
				background_hover_color	: '#CFCFCF',
				mouse					: 'press',
				onChange     			: function(page){
											LoadData(page,false);
										  }
			});
		}
});
	